package sicau.practice.community.provider;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sicau.practice.community.dto.AccessTokenDTO;
import sicau.practice.community.dto.GithubUser;

import java.io.IOException;

@Component
public class GithubProvider {

    @Value("${github.getaccesstoken.url}")
    private String getAccessTokenURL;
    @Value("${github.getuser.url}")
    private String getUserURL;

    /*
    获取accesstoken
     */
    public String getAccessToken(AccessTokenDTO accessTokenDTO){

        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url(getAccessTokenURL)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            String accesstoken = string.split("&")[0].split("=")[1];
            return accesstoken;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    根据accesstoken获取user
     */
    public GithubUser getUser(String accesstoken) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(getUserURL+accesstoken)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            GithubUser githubUser = JSON.parseObject(string, GithubUser.class);
            return githubUser;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
